#!/bin/bash

time="$(date +%Y"-"%m"-"%d"_"%k":"%M":"%S)"
cd $(cd `dirname $0`; pwd)

mysql_dir=`pwd`

echo "$time begin to install--------------------------mysql"
yum -y install libaio perl
# test centos 7
el7flag=`uname -a | grep el7`
if [[ ! -z "$el7flag" ]]; then
        oldmariadb=`rpm -qa | grep -i mariadb`
        echo "installed mariadb: $oldmariadb"
        rpm -ev --nodeps $oldmariadb
        yum install -y perl-Module-Install.noarch net-tools
fi
echo "$time uninstall mysql low version"
oldmysqls=`rpm -qa | grep -i mysql`
echo "installed mysqls: $oldmysqls"
rpm -ev --nodeps $oldmysqls


mysql_client=`ls $mysql_dir/MySQL-client*`
if [ ! -z "$mysql_client" ]; then
        echo "begin to install $mysql_client"
        rpm -ivh $mysql_client
else
        echo "mysql client not found,exit"
        exit -1
fi
mysql_devel=`ls $mysql_dir/MySQL-devel*`
if [ ! -z "$mysql_client" ]; then
        echo "begin to install $mysql_devel"
        rpm -ivh $mysql_devel
else
        echo "mysql devel not found,exit"
        exit -1
fi
mysql_server=`ls $mysql_dir/MySQL-server*`
if [ ! -z "$mysql_server" ]; then
        echo "begin to install $mysql_server"
        rpm -ivh $mysql_server
else
        echo "mysql server not found,exit"
        exit -1
fi


mysql_cnf=$mysql_dir/my.cnf
echo mysql config file is $mysql_cnf
if [ ! -f "$mysql_cnf" ];then
        echo "$mysql_cnf is not found. create now."
	touch $mysql_cnf
	echo "[client]" >> $mysql_cnf
	echo "port = 3306" >> $mysql_cnf
	echo "socket = /var/lib/mysql/mysql.sock" >> $mysql_cnf
	echo "default-character-set=utf8" >> $mysql_cnf
	echo "[mysqld]" >> $mysql_cnf
	echo "port = 3306" >> $mysql_cnf
	echo "socket = /var/lib/mysql/mysql.sock" >> $mysql_cnf
	echo "character-set-server=utf8" >> $mysql_cnf
	echo "[mysql]" >> $mysql_cnf
	echo "no-auto-rehash" >> $mysql_cnf
	echo "default-character-set=utf8" >> $mysql_cnf
        cp $mysql_cnf /etc/
        cp $mysql_cnf /usr/
else 
        echo "copy mysql config file to /etc & /usr"
	cp $mysql_cnf /etc/
        cp $mysql_cnf /usr/

fi

#重置MySQL密码
service mysql stop
rm -rf /var/lib/mysql/*
mysql_install_db
chown -R mysql:mysql /var/lib/mysql/
service mysql start
#echo "请输入新的mysql root 密码："
#read rootpassword

/usr/bin/mysqladmin password 'bxn500'
echo "mysql root 密码修改完成。"
mysql_service_process=`ps aux|grep mysqld |grep "\--pid-file"`
echo "$mysql_service_process"
if [ ! -z "$mysql_service_process" ] ; then
        echo "mysql installed SUCCESS!"
else
        echo "mysql installed failed!"
fi

#获取初始root密码
#password=`cat /root/.mysql_secret | awk -F ': ' '{print $2}'`
#if [ ! -n "$password" ]; then
#	echo default password is not found.[exit] 
#else
#	echo mysql default password is $password
	#重置MySQL密码
#fi

